package system_code.DeleteFile;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Test2 {
    public static void main(String[] args) throws IOException {
        System.out.print("请输入您要删除的文件目录:");
        Scanner scanner = new Scanner(System.in);
        File rootDir = new File(scanner.next());
        if(!rootDir.isDirectory()){
            System.out.println("您输入的目录有误~");
            return;
        }
        System.out.println("请输入您要搜索文件的关键词:");
        File key = new File(scanner.next());
        //深度优先遍历进行查找
        dfs(rootDir, key);
    }
    private static void dfs(File rootDir, File key) throws IOException {
        //将文件夹打开，获取文件夹下的文件
        File[] files = rootDir.listFiles();
        if(files == null){
            return;
        }
        for(File file : files){
            //如果是文件夹就继续向下找
            if(file.isDirectory()){
                dfs(file, key);
            }else{
                //若不是文件夹，检测是否为要删除的文件
                checkFile(file, key);
            }
        }
    }

    private static void checkFile(File file, File key) throws IOException {
        if(file.getName().contains(key.getName())){
            //若key是她的关键字
            System.out.println("您要删除的文件在" +
                    file.getCanonicalPath() + "路径下，是否要删除(Y/N)");
            Scanner scanner = new Scanner(System.in);
            String str = scanner.next();
            if(str.equals("Y")){
                //删除
                file.delete();
            }else{
                System.out.println("您取消了删除操作!");
                return;
            }
        }else{
            return;
        }
    }
}
